import axios from 'axios'
import { ElLoading } from 'element-plus'
import router from '@/router'
import Message from '@/utils/Message'

// 1.表单数据  2、json数据 3、文件数据
const contentTypeForm = "application/x-www-form-urlencoded;charset=UTF-8"
const contentTypeJson = "application/json"
const contentTypeFile = "multipart/form-data"

// 根据不同的数据类型选择不同的ContentType
const request = (config) => {
  let { url, params, dataType = 'form', showLoading = 'true' } = config
  let contentType = contentTypeForm
  if (dataType === 'json') {
    contentType = contentTypeJson
  } else if (dataType === 'file') {
    // 文件数据处理
    contentType = contentTypeFile
    let param = new FormData()
    for (let key in params) {
      param.append(key, params[key])
    }
    params = param
  }


  // 创建axios实例
  const instance = axios.create({
    baseURL: '/api',
    timeout: 10 * 1000,
    headers: {
      'Content-Type': contentType,
      'X-Requested-With': 'XMLHttpRequest',
    }
  })

  // 请求拦截
  let loading = null
  instance.interceptors.request.use(
    (config) => {
      if (showLoading) {
        loading = ElLoading.service({
          lock: true,
          text: '加载中......',
          background: 'rgba(0,0,0,0.7)',
        })
      }
      return config
    },
    (error) => {
      if (showLoading && loading) {
        loading.close()
      }
      Message.error("发送请求失败")
      return Promise.reject("发送请求失败")
    }
  )

  // 响应拦截
  instance.interceptors.response.use(
    (response) => {
      if (showLoading && loading) {
        loading.close()
      }
      const responseData = response.data
      if (responseData.status == "error") {
        if (config.errorCallback) {
          config.errorCallback()
        }
        return Promise.reject(responseData.info)
      } else {
        if (responseData.code == 200) {
          return responseData
        } else if (responseData.code == 901) {
          setTimeout(() => {
            router.push("/login")
          }, 2000)
          return Promise.reject("登录超时")
        }
      }
    },
    (error) => {
      console.log(error)
      if (showLoading && loading) {
        loading.close()
      }
      return Promise.reject("网络异常")
    }
  )

  return instance.post(url, params).catch(error => {
    Message.error(error)
    return null
  })
}

export default request